﻿using PropertyManagment.common.lang;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace PropertyManagment.common.utils {

    public enum Md5Bit{ 
        bit16 = 16,
        bit32 = 32
    }

    public class Producer {

        public string createText() {
            Random r = new Random();
            string letters = "abcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder sb = new StringBuilder();

            //添加随机的五个字母
            for (int x = 0; x < 5; x++) {
                string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
            }
            var code = sb.ToString();

            return code;
        }

        public Bitmap createImage(string code) {
            //建立Bitmap对象，绘图
            Bitmap bitmap = new Bitmap(200, 60);
            Graphics graph = Graphics.FromImage(bitmap);
            graph.FillRectangle(new SolidBrush(Color.LightGray), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);

            Random r = new Random();
            int n = 0;
            //添加随机的五个字母
            foreach (char letter in code) {
                graph.DrawString(letter.ToString(), font, new SolidBrush(Color.Black), n * 38, r.Next(0, 15));
                n++;
            }

            //混淆背景
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            return bitmap;
        }

        public string ToBitmapBase64(Bitmap bitmap) {
            //MemoryStream stream = new MemoryStream();
            //bitmap.Save(stream, ImageFormat.Jpeg);
            ////var model = File(stream.ToArray(), "image/jpeg");
            //byte[] arr = new byte[stream.Length];
            //stream.Position = 0;
            //stream.Read(arr, 0, (int)stream.Length);
            //stream.Close();
            //var base64 = Convert.ToBase64String(arr);

            var base64 = "";
            using (MemoryStream stream = new MemoryStream()) {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] arr = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, Convert.ToInt32(stream.Length));
                base64 = Convert.ToBase64String(arr);
            }

            return base64;
        }


        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string Md5(string str, Md5Bit code) {
            string strEncrypt = string.Empty;
            if (code == Md5Bit.bit16) {
                strEncrypt = Md5Hash(str).Substring(8, 16);
            }

            if (code == Md5Bit.bit32) {
                strEncrypt = Md5Hash(str);
            }

            return strEncrypt;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Md5Hash(string input) {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++) {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString().ToUpper();
        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text) {
            return Encrypt(Text, Const.DEFULT_DESKEY);
        }
        /// <summary> 
        /// DES加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey) {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(Text);
            string value = Md5Hash(sKey).Substring(0, 8);
            des.Key = ASCIIEncoding.ASCII.GetBytes(value);
            des.IV = ASCIIEncoding.ASCII.GetBytes(value);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray()) {
                ret.AppendFormat("{0:X2}", b);  //X2表示十六进制格式（大写），域宽2位，不足的左边填0。
            }
            return ret.ToString();
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text) {
            if (!string.IsNullOrEmpty(Text)) {
                return Decrypt(Text, Const.DEFULT_DESKEY);
            } else {
                return "";
            }
        }
        /// <summary> 
        /// DES解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey) {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            for (int x = 0; x < len; x++) {
                int i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            string value = Md5Hash(sKey).Substring(0, 8);
            des.Key = ASCIIEncoding.ASCII.GetBytes(value);
            des.IV = ASCIIEncoding.ASCII.GetBytes(value);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        /// <summary> 
        /// 验证密码
        /// </summary> 
        /// <param name="currentPass"></param> 
        /// <param name="encryptPass"></param> 
        /// <returns></returns> 
        public static bool passwordMatches(string currentPass, string encryptPass) {
            if (Encrypt(currentPass).Equals(encryptPass)) {
                return true;
            } else {
                return false;
            }
        }
    }
}
